package com.wang.luntan.users.service.impl;

import com.wang.luntan.common.pojo.ApiResponse;
import com.wang.luntan.common.pojo.ApiResponseEnum;
import com.wang.luntan.common.service.service.BaseServiceImpl;
import com.wang.luntan.common.util.ConstatFinalUtil;
import com.wang.luntan.users.pojo.AtAdmins;
import com.wang.luntan.users.pojo.AtUsers;
import com.wang.luntan.users.pojo.AtUsersEnum;
import com.wang.luntan.users.service.INoLoginOperService;
import com.wang.luntan.users.service.IUsersDbService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 用户不需要登陆的一些操作
 *
 * @author wangsh
 */
@Service("noLoginOperService")
@Log4j2
public class NoLoginOperServiceImpl extends BaseServiceImpl implements INoLoginOperService {
    @Autowired
    private IUsersDbService usersDbService;

    public ApiResponse<Object> operLoginSubmitService(Map<String, Object> paramsMap) {
        log.info("--loginSubmit--");
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        /* 存储多个结果,Map存储 */
        Map<String, Object> dataMapJava = new HashMap<String, Object>();
        apiResponse.setDataMapJava(dataMapJava);

        /* 接收参数 */
        String email = paramsMap.get("email") + "";
        String password = paramsMap.get("password") + "";
        String code = paramsMap.get("code") + "";
        String randSess = paramsMap.get("randSess") + "";
        String failedCount = paramsMap.get("failedCount") + "";

        if ((!"".equalsIgnoreCase(failedCount) && !"null".equalsIgnoreCase(failedCount)
                && Integer.valueOf(failedCount) > ConstatFinalUtil.CONFIG_JSON.getIntValue("session.randFailedCount"))
                || this.regexUtil.verifyCode(randSess, code)) {
            /* 查询db,处理业务逻辑 */
            Map<String, Object> condMap = new HashMap<String, Object>();
            condMap.put("email", email);
            ApiResponse<AtUsers> apiRes = this.usersDbService.findOneUsersService(condMap);
            AtUsers users = apiRes.getDataOneJava();
            /* 检验邮箱 */
            if (users != null) {
                /* 将邮箱放到request中 */
                dataMapJava.put("users", users);

                /* 检验密码 */
                if (this.encryptUtil.checkStr(password, users.getPassword())) {
                    users.setSouPass(password);
                    /* 状态必须为启用 */
                    if (users.getStatus() == AtUsersEnum.STATUS_ENABLE.getStatus()) {
                        /* 登陆成功 */
                        dataMapJava.put("users", users);
                        dataMapJava.put("lastLoginTime", users.getLastLoginTime());

                        /* 修改管理员操作 */
                        users.setLastLoginTime(new Date());

                        this.usersDbService.updateOneUsersService(users);

                        apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
                        apiResponse.setInfo(
                                ConstatFinalUtil.INFO_JSON.getString(ApiResponseEnum.STATUS_SUCCESS.getStatus() + ""),
                                Collections.EMPTY_MAP);
                        return apiResponse;
                    } else {
                        /* 状态为禁用 */
                        apiResponse.setCode(ApiResponseEnum.INFO_ACCOUNT_DISABLED.getStatus());
                        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(
                                ApiResponseEnum.INFO_ACCOUNT_DISABLED.getStatus() + ""), Collections.EMPTY_MAP);
                    }
                } else {
                    /* 密码不正确 */
                    apiResponse.setCode(ApiResponseEnum.INFO_PASS_INCORRECT.getStatus());
                    apiResponse.setInfo(
                            ConstatFinalUtil.INFO_JSON.getString(ApiResponseEnum.INFO_PASS_INCORRECT.getStatus() + ""),
                            Collections.EMPTY_MAP);
                }
            } else {
                /* 邮箱不存在 */
                apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_NOT_EXISTS.getStatus());
                apiResponse.setInfo(
                        ConstatFinalUtil.INFO_JSON.getString(ApiResponseEnum.INFO_EMAIL_NOT_EXISTS.getStatus() + ""),
                        Collections.EMPTY_MAP);
            }
        } else {
            /* 验证码正确 */
            apiResponse.setCode(ApiResponseEnum.INFO_VERIFY_CODE_INCORR.getStatus());
            apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
                    Collections.EMPTY_MAP);
        }
        /* 提示信息 */
        return apiResponse;
    }

    @Override
    public ApiResponse<Object> operAdminsLoginSubmitService(Map<String, Object> paramsMap) {
        log.info("--loginSubmit--");
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        /* 存储多个结果,Map存储 */
        Map<String, Object> dataMapJava = new HashMap<String, Object>();
        apiResponse.setDataMapJava(dataMapJava);

        /* 接收参数 */
        String email = paramsMap.get("email") + "";
        String password = paramsMap.get("password") + "";
        String code = paramsMap.get("code") + "";
        String randSess = paramsMap.get("randSess") + "";
        /* 获取当前登陆的ip */
        String ip = paramsMap.get("ip") + "";
        // 如果登录失败次数不为空字符串也不为null而且大于3次或者验证码验证正确
        if (this.regexUtil.verifyCode(randSess, code)) {
            /* 查询db,处理业务逻辑 */
            Map<String, Object> condMap = new HashMap<String, Object>();
            condMap.put("email", email);
            ApiResponse<AtAdmins> apiRes = this.usersDbService.findOneAdminsService(condMap);
            AtAdmins admins = apiRes.getDataOneJava();
            if (admins == null) {
                /* 邮箱不存在 */
                apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_NOT_EXISTS.getStatus());
                apiResponse.setInfo(
                        ConstatFinalUtil.INFO_JSON.getString(ApiResponseEnum.INFO_EMAIL_NOT_EXISTS.getStatus() + ""),
                        Collections.EMPTY_MAP);
                return apiResponse;
            }
            int failedCount = admins.getFailedCount();
            /* 检验邮箱 */
            if (admins != null) {
                /* 检验密码 */
                if (this.encryptUtil.checkStr(password, admins.getPassword())) {
                    /* 状态必须为启用 */
                    if (admins.getStatus() == AtUsersEnum.STATUS_ENABLE.getStatus()) {
                        /* 登陆成功 */
                        admins.setLastLoginTime(new Date());

                        /* 修改管理员操作 */
                        admins.setLoginCount(admins.getLoginCount() + 1);
                        /* 输入正确的时候,要重置 */
                        admins.setFailedCount(0);
                        this.usersDbService.updateOneAdminsService(admins);

                        apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
                        apiResponse.setInfo(
                                ConstatFinalUtil.INFO_JSON.getString(ApiResponseEnum.STATUS_SUCCESS.getStatus() + ""),
                                Collections.EMPTY_MAP);
                        return apiResponse;
                    } else {
                        /* 状态为禁用 */
                        apiResponse.setCode(ApiResponseEnum.INFO_ACCOUNT_DISABLED.getStatus());
                        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(
                                ApiResponseEnum.INFO_ACCOUNT_DISABLED.getStatus() + ""), Collections.EMPTY_MAP);
                    }
                } else {

                    /* 密码不正确 */
                    dataMapJava.put("adminsEmail", admins.getEmail());
                    admins.setFailedCount(failedCount + 1);
                    admins.setFailedTime(new Date());
                    this.usersDbService.updateOneAdminsService(admins);
                    apiResponse.setCode(ApiResponseEnum.INFO_PASS_INCORRECT.getStatus());
                    apiResponse.setInfo(
                            ConstatFinalUtil.INFO_JSON.getString(ApiResponseEnum.INFO_PASS_INCORRECT.getStatus() + ""),
                            Collections.EMPTY_MAP);
                }
            }
        } else {
            /* 验证码不正确 */
            apiResponse.setCode(ApiResponseEnum.INFO_VERIFY_CODE_INCORR.getStatus());
            apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
                    Collections.EMPTY_MAP);
        }
        /* 提示信息 */
        return apiResponse;
    }

    @Override
    public ApiResponse<Object> operRegisterSubmitService(Map<String, Object> paramsMap) {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();
        log.info("--registerSubmit--");
        /* 接收参数 */
        String email = paramsMap.get("email") + "";
        String password = paramsMap.get("password") + "";
        String code = paramsMap.get("code") + "";
        String randSess = paramsMap.get("randSess") + "";

        if (this.regexUtil.verifyCode(randSess, code)) {
            /* 创建对象 */
            AtUsers users = new AtUsers();
            /* 赋值 */
            users.setEmail(email);
            users.setPassword(this.encryptUtil.encodeStr(password));
            /* 设置状态 */
            users.setStatus(AtUsersEnum.STATUS_ENABLE.getStatus());

            users.setCreateTime(new Date());
            users.setUpdateTime(new Date());
            users.setLastLoginTime(new Date());
            users.setSouPass(password);

            apiResponse = this.usersDbService.saveOneUsersService(users);
            log.info("==注册成功=={}", apiResponse.toJSON());
            if (apiResponse.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus()) {
                apiResponse.setInfo(
                        ConstatFinalUtil.INFO_JSON.getString(ApiResponseEnum.INFO_REGISTER_SUCCESS.getStatus() + ""),
                        Collections.EMPTY_MAP);
            }
        } else {
            /* 验证码正确 */
            apiResponse.setCode(ApiResponseEnum.INFO_VERIFY_CODE_INCORR.getStatus());
            apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
                    Collections.EMPTY_MAP);
        }
        return apiResponse;
    }

    @Override
    public ApiResponse<Object> operEmailVerfySendService(Map<String, Object> paramsMap) {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();

        /* 根据邮箱来操作 */
        String email = paramsMap.get("email") + "";
        String contextPath = paramsMap.get("contextPath") + "";
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<Object> operEmailVerfyService(Map<String, Object> paramsMap) {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();

        String email = paramsMap.get("email") + "";
        String code = paramsMap.get("code") + "";

        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<Object> operForgetPassSubmit(Map<String, Object> paramsMap) {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();

        /* 根据邮箱来操作 */
        String email = paramsMap.get("email") + "";
        String code = paramsMap.get("code") + "";
        String randSess = paramsMap.get("randSess") + "";
        String contextPath = paramsMap.get("contextPath") + "";

        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<Object> operResetPass(Map<String, Object> paramsMap) {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();

        /* 根据邮箱来操作 */
        String email = paramsMap.get("email") + "";
        String code = paramsMap.get("code") + "";

        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<Object> operResetPassSubmit(Map<String, Object> paramsMap) {
        ApiResponse<Object> apiResponse = new ApiResponse<Object>();

        /* 根据邮箱来操作 */
        String email = paramsMap.get("email") + "";
        String password = paramsMap.get("password") + "";
        String randSess = paramsMap.get("randSess") + "";
        String code = paramsMap.get("code") + "";
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<AtUsers> operAddUsersTokenService(AtUsers users) {
        ApiResponse<AtUsers> apiResponse = new ApiResponse<AtUsers>();
        try {
            String token = users.getTokenStr();
            if (token == null || "".equalsIgnoreCase(users.getTokenStr())) {
                token = UUID.randomUUID().toString();
                users.setTokenStr(token);
            }
            /* 将token添加到redis中 */
            String key = redisUtil.KEY_USERS_TOKEN + users.getTokenStr();
            boolean flag = this.redisUtil.put(key, users.toJSON().toJSONString(),
                    Integer.valueOf(ConstatFinalUtil.CONFIG_JSON.getString("timeout.token")));
            if (flag) {
                apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
            }
        } catch (Exception e) {
            log.error("存储Redis时失败了,", e);
        }
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    @Override
    public ApiResponse<AtAdmins> operAddAdminsTokenService(AtAdmins admins) {
        ApiResponse<AtAdmins> apiResponse = new ApiResponse<AtAdmins>();
        try {
            String token = admins.getTokenStr();
            if (token == null || "".equalsIgnoreCase(admins.getTokenStr())) {
                token = UUID.randomUUID().toString();
                admins.setTokenStr(token);
            }
            /* 将token添加到redis中 */
            String key = redisUtil.KEY_ADMINS_TOKEN + admins.getTokenStr();
            boolean flag = this.redisUtil.put(key, admins.toJSON().toJSONString(),
                    Integer.valueOf(ConstatFinalUtil.CONFIG_JSON.getString("timeout.token")));
            if (flag) {
                apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
            }
        } catch (Exception e) {
            log.error("存储Redis时失败了,", e);
        }
        apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
        return apiResponse;
    }

    public ApiResponse<Object> thawAccountService(Map<String, Object> paramsMap) {
        return null;
    }

}
